package com.qingfeng.client.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qingfeng.client.bean.LogisticsCompany;
import com.qingfeng.client.bean.Seller;
import com.qingfeng.client.bean.Store;
import com.qingfeng.client.bean.StoreGoodsGroup;
import com.qingfeng.client.dao.LogisticsCompanyMapper;
import com.qingfeng.client.dao.SellerMapper;
import com.qingfeng.client.dao.StoreMapper;
import com.qingfeng.client.service.GoodsTypeService;
import com.qingfeng.client.service.StoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author ff
 * @Data 2017/10/25 10:17
 */
@RestController
@Api(tags = "店铺管理")
@RequestMapping("/api/store")
@SessionAttributes("auth")
public class StoreApi extends BaseV1Api {

    @Resource
    private StoreService storeService;

    @Resource
    private SellerMapper sellerDao;

    @Resource
    private StoreMapper storeDao;

    @Resource
    private LogisticsCompanyMapper logisticsCompanyDao;

    @Resource
    private GoodsTypeService goodsTypeService;

    @ApiOperation("获取我的店铺信息")
    @GetMapping(value = "/myStore")
    public Object myStore() {
        Seller sellerBean = getUser();
        Store storeBean = storeService.myStore(sellerBean.getStoreId());
        if (storeBean == null) {
            return error(null);
        } else {
            return success(storeBean);
        }
    }


    /**
     * 创建一个新的店铺
     * @param jsonObject name店铺名称，address店铺地址
     * @return
     */
    @ApiOperation("创建我的店铺信息")
    @PostMapping(value = "/create")
    public Object create(@RequestBody JSONObject jsonObject) {
        String msg = StringUtils.EMPTY;
        try {
            Store storeBean = new Store();
            storeBean.setName(jsonObject.getString("name"));
            storeBean.setAddress(jsonObject.getString("address"));
            storeBean.setIcon(jsonObject.getString("icon"));
            Seller sellerBean = getUser();
            storeBean.setStoreMaster(sellerBean.getId());
            Integer id = storeService.create(storeBean);
            if (id == null || id <= 0) {
                msg = "店铺名已存在";
            } else {
                sellerDao.updateById(sellerBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = "您已有店铺，无法再次新建";
        }
        if (StringUtils.isEmpty(msg)) {
            return success(null);
        } else {
            return error(msg);
        }
    }


    /**
     * 获取父分类下的所有自分类
     *
     * @param parenId
     * @return
     */
    @ApiOperation("获取父类分类")
    @GetMapping(value = "/getGroup/{parentId}")
    public Object getGroup(@PathVariable(value = "parentId") Long parenId) {
        Seller sellerBean = getUser();
        List list = storeService.queryGroup(sellerBean.getStoreId(), parenId);
        if (list == null) {
            return error(null);
        } else {
            return success(list);
        }
    }

    /**
     * 获取所有分类信息
     *
     * @return
     */
    @ApiOperation("获取所有分类信息")
    @GetMapping(value = "/getGroup")
    public Object getAllGroup() {
        Seller sellerBean = getUser();
        List list = storeService.queryGroup(sellerBean.getStoreId(), null);
        if (list == null) {
            return error(null);
        } else {
            return success(list);
        }
    }

    /**
     * 为店铺添加一个分组
     * @param storeGoodsGroupBean
     * @return
     */
    @ApiOperation("为店铺添加一个分组")
    @PostMapping(value = "/addGroup")
    public Object addGroup(@RequestBody StoreGoodsGroup storeGoodsGroupBean){
        Seller sellerBean = getUser();
        storeGoodsGroupBean.setStoreId(sellerBean.getStoreId());
        Integer id = storeService.addGroup(storeGoodsGroupBean);
        if (id>0){
            return success(null);
        }else {
            return error(null);
        }
    }

    /**
     * 删除一个店铺分组
     * @param id
     * @return
     */
    @ApiOperation("删除一个店铺分组")
    @GetMapping(value = "/deleteGroup/{id}")
    public Object deleteGroup(@PathVariable(value = "id")Long id){
        Seller sellerBean = getUser();
        boolean result = storeService.deleteGroup(id,sellerBean.getStoreId());
        return returnBoolean(result);
    }

    /**
     * 更新店铺信息
     *
     * @param storeBean
     * @return
     */
    @ApiOperation("更新店铺信息")
    @PostMapping(value = "/update")
    @ResponseBody
    public Object update(@RequestBody Store storeBean) {
        Seller sellerBean = getUser();
        int result = 0;
        if (storeBean != null) {
            storeBean.setId(sellerBean.getStoreId());
            result = storeDao.updateById(storeBean);
        }
        if (result>0){
            return success(null);
        }else {
            return error(null);
        }
    }

    @ApiOperation("修改店铺物流配置")
    @PostMapping(value = "/updateLogisticsCompany")
    public Object updateLogisticsCompany(@RequestBody LogisticsCompany logisticsCompanyBean){
        Seller seller = getUser();
        logisticsCompanyDao.updateById(logisticsCompanyBean);
        return success("修改完成");
    }

    /**
     * 为店铺添加一个物流公司
     * @param logisticsCompanyBean
     * @return
     */
    @ApiOperation("添加店铺物流配置")
    @PostMapping(value = "/addLogisticsCompany")
    public Object addLogisticsCompany(@RequestBody LogisticsCompany logisticsCompanyBean) {
        Seller sellerBean = getUser();
        List<LogisticsCompany> logisticsCompanies = logisticsCompanyDao.getByStoreId(sellerBean.getStoreId());
        boolean haveDefault=logisticsCompanies.stream().anyMatch(
                logisticsCompany -> logisticsCompany.getDefaultAddr()!=null
                        && logisticsCompany.getDefaultAddr()==1
                        && logisticsCompany.getType() == logisticsCompanyBean.getType()
        );
        //设置默认自提地址，或者默认邮寄发货地址
        if (haveDefault){
            logisticsCompanyBean.setDefaultAddr(0);
        }else {
            logisticsCompanyBean.setDefaultAddr(1);
        }
         haveDefault=logisticsCompanies.stream().anyMatch(
                logisticsCompany -> logisticsCompany.getDefaultAddr()!=null
                        && logisticsCompany.getDefaultRecv() !=null
                        && logisticsCompany.getDefaultRecv()==1
                        && logisticsCompany.getType() == logisticsCompanyBean.getType()
        );
        //设置默认收货地址，或者默认邮寄发货地址
        if (haveDefault){
            logisticsCompanyBean.setDefaultRecv(0);
        }else {
            logisticsCompanyBean.setDefaultRecv(1);
        }

        if(logisticsCompanyBean.getType()==2){
            logisticsCompanyBean.setName(logisticsCompanyBean.getContactsName());
        }

        logisticsCompanyBean.setStoreId(sellerBean.getStoreId());
        logisticsCompanyBean.setId(null);
        if (logisticsCompanyDao.insert(logisticsCompanyBean) > 0) {
            return success(null);
        } else {
            String msg = "该物流公司已被录入";
            return error(msg);
        }
    }

    /**
     * 获取店铺所属的物流公司
     * @return
     */
    @ApiOperation("获取店铺物流信息")
    @GetMapping(value = "/getLogisticsCompany")
    public Object getLogisticsCompany() {
        Seller sellerBean = getUser();
        List list = logisticsCompanyDao.getByStoreId(sellerBean.getStoreId());
        List goodsType=goodsTypeService.get();
        Map map = new HashMap();
        map.put("list",list);
        map.put("goodsType",goodsType);
        if (list != null) {
            return success(map);
        } else {
            return error(null);
        }
    }

    /**
     * 删除店铺所属物流
     * @param id
     * @return
     */
    @ApiOperation("删除店铺物流")
    @GetMapping(value = "/deleteLogisticsCompany/{id}")
    public Object deleteLogisticsCompany(@PathVariable(value = "id") Long id){
        Seller sellerBean = getUser();
        LogisticsCompany lo = logisticsCompanyDao.selectById(id);
        if(lo.getDefaultRecv() !=null && lo.getDefaultRecv()==1){
            return error("默认收货地址，不能删除");
        }
        if (lo.getDefaultAddr() != null && lo.getDefaultAddr()==1){
            return error("默认发货地址不能删除");
        }
        int result = logisticsCompanyDao.deleteByIdAndStoreId(id,sellerBean.getStoreId());
        if (result>0){
            return success("删除成功");
        }else {
            return error("删除失败");
        }
    }

    @ApiOperation("设置默认发货地址")
    @PostMapping("/setDefaultAddress/{id}")
    public Object setDefaultAddress(@PathVariable("id")Integer id){
        Seller seller = getUser();
        LogisticsCompany logisticsCompany = logisticsCompanyDao.selectById(id);
        logisticsCompanyDao.updateDefaultAddrByStoreId(0,seller.getStoreId());
        logisticsCompany.setDefaultAddr(1);
        logisticsCompanyDao.updateById(logisticsCompany);
        return success("设置默认发货地址成功");
    }

    @ApiOperation("设置默认收货地址")
    @PostMapping("/setDefaultRecv/{id}")
    public Object setDefaultRecv(@PathVariable("id")Integer id){
        Seller seller = getUser();
        LogisticsCompany logisticsCompany = logisticsCompanyDao.selectById(id);
        logisticsCompanyDao.updateDefaultRecvByStoreId(0,seller.getStoreId());
        logisticsCompany.setDefaultRecv(1);
        logisticsCompanyDao.updateById(logisticsCompany);
        return success("设置默认收货地址成功");
    }


    //todo 废弃接口设置邮费
    @RequestMapping(value = "/setPostage")
    @ResponseBody
    public Object setPostage(@RequestBody Store storeBean){
        Integer id = storeBean.getId();
        int postage = storeBean.getPostage();
        boolean flag = storeService.setPostage(id,postage);
        if (!flag){
            return error("修改邮费失败！");
        }
        return success("修改邮费成功！");
    }

}
